package com.ruoyi.stock.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.stockTypeeEnums;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.stock.domain.*;
import com.ruoyi.stock.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 持仓咨询Controller
 * 
 * @author ruoyi
 * @date 2024-12-30
 */
@RestController
@RequestMapping("/stock/stockinquery")
@Api( tags = "持仓咨询")
public class StockInqueryController extends BaseController
{
    @Autowired
    private IStockInqueryService stockInqueryService;

    @Autowired
    private IStockDfcfService stockDfcfService;
    @Autowired
    private IStockUserService stockUserService;

    @Autowired
    private IStockHeaderSetttingService stockHeaderSetttingService;



    @Autowired
    private IStockConfigService stockConfigService;

    /**
     * 查询持仓咨询列表 /stock/stockinquery/list
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询咨询信息")
    @Log(title = "查询咨询信息bug ", businessType = BusinessType.EXPORT)
    public TableDataInfo list(StockInquery stockInquery)
    {
        List<StockInquery>  fieldStockInqueryResult=new ArrayList<StockInquery>();
        StockConfig stockConfig= stockConfigService.selectStockConfigById(2l);
        stockConfig.getContent();
        int inqueryCount= Integer.parseInt(stockConfig.getContent());
        inqueryCount=inqueryCount+1;
        stockConfig.setContent(inqueryCount+"");
        stockConfigService.updateStockConfig(stockConfig);
        /////////////////
        StockUser stockUser=new StockUser();
        stockUser.setSysUserid(SecurityUtils.getUserId());
        stockUser= stockUserService.selectStockUserList(stockUser).get(0);
        //////////////
        if(StringUtils.isEmpty(stockUser.getMemberType())){
            throw  new GlobalException("暂无询价次数，请先开通会员");
        }
        /////////////////
        //当时
        if("1".equals(stockUser.getMemberType())){
            int inqueryCounts= Integer.parseInt(stockUser.getInqueryCount());
            // 询价次数减少
            if(inqueryCounts>0){
                if(stockInquery.getIsVaild()!=null){
                    inqueryCounts=inqueryCounts-1;
                    stockUser.setInqueryCount(inqueryCounts+"");
                    stockUserService.updateStockUser(stockUser);
                }
            }else{
                throw  new GlobalException("对不起，您的免费询价已用完");
            }
        }

        if(StringUtils.isEmpty(stockInquery.getSecurityCode())){
            throw  new GlobalException("请输入证券代码或名称");
        }

        try {
        // 更新查询次数
        //////////////////
        String[] timeperionArr=stockInquery.getTimePerion().split(",");
        String[]  stockStructueArr=stockInquery.getStockStructue().split(",");
        StockHeaderSettting stockHeaderSettting=new StockHeaderSettting();
        StockInquery stockInqueryField=new StockInquery();
        /////查询用；
        List<StockInquery>  fieldStockInquerylist=new ArrayList<StockInquery>();
        // 最终结构

             // 首先拼接要寻找字段的key值；
            for (String timeperionParam : timeperionArr) {
                 //timeperionParam = timeperionParam.replaceAll("个月", "")+"m";
                 int i=0;

                for (String stockStructueParam : stockStructueArr) {
                    i=i+1;
                    String initstockStructueParam=stockStructueParam;
                    if(!(stockTypeeEnums.香草.getCode()+"").equals(stockInquery.getStockType())) {
                        stockStructueParam=stockStructueParam.replaceAll("c","-");
                    }else{
                        stockStructueParam=stockStructueParam+" ";
                    }
                    String   resultTimeperionParam=stockStructueParam+timeperionParam.replaceAll("个月", "")+"m";
                    // 拿到key值；取寻找字段。
                    stockHeaderSettting.setHeaderName(resultTimeperionParam);
                    List<StockHeaderSettting> stockHeaderSetttings=stockHeaderSetttingService.selectStockHeaderSetttingList(stockHeaderSettting);
                    if(stockHeaderSetttings.size()==0){
                        break;
                     }
                    String filedParam= stockHeaderSetttings.get(0).getHeaderField();
                    //////////////////////////再根据该字段排序
                    stockInqueryField.setSecurityCode(stockInquery.getSecurityCode());
                    stockInqueryField.setFieldParam(filedParam);
                    stockInqueryField.setStockType(stockInquery.getStockType());
                    //为配合前端的值传反了；
                    if((stockTypeeEnums.香草.getCode()+"").equals(stockInquery.getStockType())) {
                        stockInqueryField.setStockType(stockTypeeEnums.雪球.getCode()+"");
                    }else{
                        stockInqueryField.setStockType(stockTypeeEnums.香草.getCode()+"");
                    }
                    ////////////////////
                    fieldStockInquerylist= stockInqueryService.selectStockInqueryListByField(stockInqueryField);
                    if(fieldStockInquerylist.size()>0){
                        if(i!=1){
                            fieldStockInquerylist.get(0).setSecurityCode("");
                            fieldStockInquerylist.get(0).setSecurityName("");
                        }
                        fieldStockInquerylist.get(0).setMarginRatio(stockInquery.getMarginRatio());
                        fieldStockInquerylist.get(0).setStockType(stockInquery.getStockType());
                        fieldStockInquerylist.get(0).setTimePerion(timeperionParam);
                        fieldStockInquerylist.get(0).setStockStructue(initstockStructueParam);
                        fieldStockInqueryResult.add(fieldStockInquerylist.get(0));
                    }
                }
        }
        }catch (Exception e){
            throw  new GlobalException("当前搜索的内容不存在");
           // return getDataTable(fieldStockInqueryResult);
        }
      //  stockInquery.setStockStructue(null);
       // stockInquery.setTimePerion(null);
       // List<StockInquery> list = stockInqueryService.selectStockInqueryList(stockInquery);
        if(fieldStockInqueryResult.size()==0){
            throw  new GlobalException("当前搜索的内容不存在");
        }
        return getDataTable(fieldStockInqueryResult);
    }



    /**
     * 查询持仓咨询列表
     */
    @GetMapping("/pclist")
    @ApiOperation(value = "查询咨询信息")
    public TableDataInfo pclist(StockInquery stockInquery)
    {

        stockInquery.setStockStructue(null);
        stockInquery.setTimePerion(null);
        startPage();
        List<StockInquery> list = stockInqueryService.selectStockInqueryList(stockInquery);
        return getDataTable(list);
    }


    /**
     * 查询持仓咨询列表
     */
    @GetMapping("/appthinklist")
    @ApiOperation(value = "查询咨询信息")
    public TableDataInfo appThinklist(StockInquery stockInquery)
    {
        stockInquery.setStockStructue(null);
        stockInquery.setTimePerion(null);
        if("1".equals(stockInquery.getStockType())){
            stockInquery.setStockType("2");
        }else{
            if("2".equals(stockInquery.getStockType())){
                stockInquery.setStockType("1");
            }
        }


        startPage();
        List<StockInquery> list = stockInqueryService.selectStockInqueryList(stockInquery);
        for(int i=0;i<list.size();i++){
            list.get(i).setLastPrice(("10.25"));
        }
        return getDataTable(list);
    }



    @GetMapping("/listBydfcf")
    @ApiOperation(value = "首页东方财富查询咨询信息")
    public AjaxResult listBydfcf(StockDfcf stockDfcf ) throws Exception {
//        String url="http://38.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=20&po=1&np=1&fltt=2&invt=2&dect=1&fid=f3&fs=m:1+t:2,m:1+t:23";
//        String[] url1=url.split("&");
//        JSONObject wxJson = JSON.parseObject(HttpClientSslUtils.doGet(url));
//        JSONObject  obj=   JSON.parseObject(wxJson.get("data").toString());
//        JSONArray obj1=  obj.getJSONArray("diff");
        List<StockInquery> list=new ArrayList<StockInquery>();
//        for(int i=0;i<obj1.size();i++){
//            StockInquery stockInquery=new StockInquery();
//            stockInquery.setSecurityCode(JSON.parseObject(obj1.get(i).toString()).get("f12").toString());
//            List<StockInquery> list1 =stockInqueryService.selectStockInqueryList(stockInquery);
//            if(list1.size()>0){
//                stockInquery=list1.get(i);
//            }
//            stockInquery.setSecurityName(JSON.parseObject(obj1.get(i).toString()).get("f14").toString());
//            stockInquery.setLastPrice(new BigDecimal(JSON.parseObject(obj1.get(i).toString()).get("f2").toString()));
//            stockInquery.setLatestIncrease(new BigDecimal(JSON.parseObject(obj1.get(i).toString()).get("f25").toString()));
//            stockInquery.setCirculationMarketValue(new BigDecimal(JSON.parseObject(obj1.get(i).toString()).get("f2").toString()));
//            // stockInquery.set(JSON.parseObject(obj1.get(0).toString()).get("f12").toString());
//            list.add(stockInquery);
//        }
        //
        startPage();
        List<StockDfcf>  list1= stockDfcfService.selectStockDfcfList(stockDfcf);

        StockUser stockUser=new StockUser();
        try {
            //防止用户未登录
            stockUser.setSysUserid( SecurityUtils.getUserId());
            stockUser= stockUserService.selectStockUserList(stockUser).get(0);
        }catch (Exception e){

        }

        for(StockDfcf stockDfcf1:list1){
            StockInquery stockInquery=new StockInquery();
            stockInquery.setSecurityCode(stockDfcf1.getSecurityCode());
            if(stockUser.getIsMember()!=null){
                if(stockUser.getIsMember()==1) {
                    //当是会员的时候看后面的信息
                    List<StockInquery> list2 = stockInqueryService.selectStockInqueryList(stockInquery);
                    if (list2.size() > 0) {
                        stockInquery = list2.get(0);
                    }
                }
            }
            stockInquery.setSecurityCode(stockDfcf1.getSecurityCode());
            stockInquery.setSecurityName(stockDfcf1.getSecurityName());
            stockInquery.setLastPrice((stockDfcf1.getLastPrice()));
            stockInquery.setLatestIncrease((stockDfcf1.getLatestIncrease()));
            //stockInquery.setCirculationMarketValue(new BigDecimal(stockDfcf1.getc));
            // stockInquery.set(JSON.parseObject(obj1.get(0).toString()).get("f12").toString());
            list.add(stockInquery);
        }
        //stockDfcf.setp
      //  List<StockInquery> list = stockInqueryService.selectStockInqueryList(stockInquery);
        return success(list);
    }


    @PostMapping("/importDataxc")
    public AjaxResult importDataxc(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<StockInquery> util = new ExcelUtil<StockInquery>(StockInquery.class);
        List<StockInquery> stockInquery = util.importExcel(file.getInputStream());
        for(int i=0;i<stockInquery.size();i++){
            stockInquery.get(i).setCreateTime(new Date());
            stockInquery.get(i).setCreateBy(SecurityUtils.getUsername());
            stockInquery.get(i).setStockType("2");
            stockInqueryService.insertStockInquery(stockInquery.get(i));
        }
        //String operName = getUsername();
        //String message = userService.importUser(userList, updateSupport, operName);
        return success(stockInquery.size());
    }


    @PostMapping("/importDataxq")
    public AjaxResult importDataxq(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<StockInquery> util = new ExcelUtil<StockInquery>(StockInquery.class);
        List<StockInquery> stockInquery = util.importExcel(file.getInputStream());
        for(int i=0;i<stockInquery.size();i++){
            stockInquery.get(i).setCreateTime(new Date());
            stockInquery.get(i).setCreateBy(SecurityUtils.getUsername());
            stockInquery.get(i).setStockType("1");
            stockInqueryService.insertStockInquery(stockInquery.get(i));
        }
        //String operName = getUsername();
        //String message = userService.importUser(userList, updateSupport, operName);
        return success(stockInquery.size());
    }


    /**
     * 导出持仓咨询列表
     */
    @Log(title = "持仓咨询", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StockInquery stockInquery)
    {
        List<StockInquery> list = stockInqueryService.selectStockInqueryList(stockInquery);
        ExcelUtil<StockInquery> util = new ExcelUtil<StockInquery>(StockInquery.class);
        util.exportExcel(response, list, "持仓咨询数据");
    }

    /**
     * 获取持仓咨询详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(stockInqueryService.selectStockInqueryById(id));
    }

    /**
     * 新增持仓咨询
     */
    @Log(title = "持仓咨询", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StockInquery stockInquery)
    {
        return toAjax(stockInqueryService.insertStockInquery(stockInquery));
    }

    /**
     * 修改持仓咨询
     */
    @Log(title = "持仓咨询", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StockInquery stockInquery)
    {
        return toAjax(stockInqueryService.updateStockInquery(stockInquery));
    }

    /**
     * 删除持仓咨询
     */
    @Log(title = "持仓咨询", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(stockInqueryService.deleteStockInqueryByIds(ids));
    }
}
